<template>
  <div>
    <el-menu>
      <el-menu-item disabled>
        <b style="color: red; font-size: 30px;">{{this.$store.state.VueName}}</b>
      </el-menu-item>
    </el-menu>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span> <b style="color: #606266; font-size: 30px;">账号注册</b></span>
      </div>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" >
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" autocomplete="off" class="input"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password" autocomplete="off" class="input"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off" class="input"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="password">
          <el-input  v-model="ruleForm.name" autocomplete="off" class="input"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" >
          <el-radio-group v-model="ruleForm.sex">
            <el-radio :label=0 border>女</el-radio>
            <el-radio :label=1 border>男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
              v-model="ruleForm.birthday"
              type="date"
              placeholder="选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="ruleForm.email" class="input"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="checkCode">
          <el-input v-model="ruleForm.checkCode" autocomplete="off" class="inputX"></el-input>
          <el-button type="primary" :disabled="btn.disableX" round @click="sendCode('ruleForm')" size="small">
            {{ btn.defaultTitle }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">注册</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <router-link to="/login">已有账号？点击登录
          </router-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    let accountInput = (rule, value, callback) => {//账号的实时输入
      //console.log(val);
      if(value === ''){
        callback(new Error('请输入要注册账号'));
      }else{
        let codeReg = new RegExp("[A-Za-z0-9]+"), //正则 英文+数字；
            len=value.length,
            str='';
        if (len>=6 && len<=18){
          for(let i=0;i<len;i++){
            if(codeReg.test(value[i])){
              str+=value[i];
            }
          }
          if(str.length !== len){
            this.ruleForm.username='';
            callback(new Error('请输入英文和数字!'));
          }else{
            //判定满足条件的注册
            callback();
          }
        }else {
           callback(new Error('长度在 6 到 18 个字符!'));
        }
      }
    };
    return {
      btn: {
        disableX: false,
        time: 10,
        defaultTitle: '发送邮箱验证码',
      },
      ruleForm: {
        age:'',
        username: '',
        password: '',
        checkPass: '',
        birthday: '',
        email: '',
        checkCode: '',
        role: '',
        sex: ''
      },
      rules: {
        password: [
          {validator: validatePass, trigger: 'blur', required: true}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur', required: true}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        username: [
          {validator: accountInput, trigger: 'blur', required: true }
        ],
        checkCode: [
          {min: 0, max: 9, message: '请输入正确的验证码!', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别!', trigger: 'blur'},
        ]
      },
    };
  },
  methods: {
    submitForm(formName) {
      //计算年龄
      this.calculateAge();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post('user/add/'+this.ruleForm.checkCode,this.ruleForm).then(resp => {
            if (resp.flag == true) {
              this.$message.success("注册成功");
              this.$router.push('/login')
            } else {
              console.log("注册失败!")
            }
          })
        } else {
          this.$message.info("检查输入的的格式是否正确!")
          console.log('error submit!!');
          return false;
        }
      });
    },
    //计算年龄的方法
    calculateAge(){
      //Tue Apr 13 2021 00:00:00 GMT+0800 (中国标准时间)
      if(this.ruleForm.birthday != null){
        let nowDate = new Date().getFullYear();
        let birthday = this.ruleForm.birthday.toString().substring(11,15);
        let age = parseInt(nowDate)-parseInt(birthday);
        this.ruleForm.age=age;
        console.log(this.ruleForm.age);
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    sendCode(formName) {
      console.log("正在发送验证码");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post('/user/sendEmail/' + this.ruleForm.email).then(resp => {
            console.log(resp.data)
            if (resp.flag == true) {
              console.log("验证码发送成功!")
              this.$messageBox("验证码已经发送到邮箱,请到邮箱查看!","提示:",'info')
            } else {
              this.$messageBox("验证码发送失败!","提示:",'info')
            }
          })
        } else {
          this.$message.info("检查输入的的格式是否正确!")
          console.log('error submit!!');
          return false;
        }
      });
    },
  }
}
</script>
<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  position: relative;
  width: 800px;
  margin: 0 auto;
  top: 40px;
}

.input {
  width: 60%;
}

.inputX {
  width: 120px;
}
</style>